const BaseController = require('./baseController')

class StoryController extends BaseController {
  get modelName () {
    return 'Story'
  }

  async findBythemeId () {
    const { ctx } = this
    const { _id: storythemeId } = ctx.params
    let rz = await ctx.model[this.modelName].find({ storythemeId }).lean()
    let statis = {
      join: 0,
      comment: 0,
      like: 0,
      income: 0
    }
    let midObj = {}
    if (rz.length) {
      this._.forEach(rz, (item, index) => {
        statis.comment += (item.comment && item.comment.length) || 0
        statis.like += (item.like && item.like.length) || 0
        statis.income += item.income || 0
        if (!midObj[item.userId]) {
          midObj[item.userId] = 1
          statis.join += 1
        }
      })
    }
    let body = {
      statis,
      list: rz
    }
    ctx.body = body
    return body
  }

  async updateLikeList () {
    // TODO 不能重复点赞
    const { ctx } = this
    const { _id } = ctx.params
    let data = ctx.request.body
    let isExit = await ctx.model[this.modelName].findOne({
      _id,
      like: { $elemMatch: { userId: data.userId } }
    })
    if (isExit) {
      ctx.body = '已经点赞'
      return
    }

    let origin = await ctx.model[this.modelName].findOne({
      _id,
      userId: data.userId
    }).lean()
    let list = origin.like || []
    list.push(data)
    let res = await ctx.model[this.modelName].findOneAndUpdate(
      { _id },
      {
        $set: {
          like: list
        }
      }
    )
    ctx.body = res
    return res
  }

  async updateCommentList () {
    const { ctx } = this
    const { _id } = ctx.params
    let data = ctx.request.body
    let origin = await ctx.model[this.modelName].findById(_id).lean()
    let list = origin.comment || []
    list.push(data)

    let res = await ctx.model[this.modelName].findOneAndUpdate(
      { _id },
      {
        $set: {
          comment: list
        }
      }
    )
    ctx.body = res
    return res
  }
}

module.exports = StoryController
